import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { delCartAPI, addCartAPI, getCartAPI } from '@/apis/cart'
import { useUserStore } from '@/stores/user'


export const useCartStore = defineStore('cart', () => {
  // 分类列表
  const cartList = ref([])
  const userStore = useUserStore()
  // 是否登录
  const isLogin = computed(() => {
    return userStore.userInfo.token ? true : false
  })

  const isAllSelected = computed(() => {
    if (cartList.value.length === 0) return false
    return cartList.value.every(item => item.selected)
  })

  const totalNumHeader = computed(() => {
    return cartList.value.reduce((pre, item) => {
      return pre + item.count
    }, 0)
  })
  const totalPriceHeader = computed(() => {
    return cartList.value.reduce((pre, item) => {
      return pre + item.count * item.price
    }, 0).toFixed(2)
  })

  const totalNumSelected = computed(() => {
    return cartList.value.filter(item => item.selected).reduce((pre, item) => {
      return pre + item.count
    }, 0)
  })
  const totalPriceSelected = computed(() => {
    return cartList.value.filter(item => item.selected).reduce((pre, item) => {
      return pre + item.count * item.price
    }, 0).toFixed(2)
  })

  const updateCart = async () => {
    const res = await getCartAPI()
    cartList.value = res.result
  }

  const addCart = async (good) => {
    if (isLogin.value) {
      await addCartAPI(good.skuId, good.count)
      updateCart()
    } else {
      const findResult = cartList.value.find(item => item.skuId === good.skuId)
      if (findResult) {
        findResult.count += good.count
      } else {
        cartList.value.push(good)
      }
    }
  }

  const delCart = async (skuId) => {
    if (isLogin.value) {
      await delCartAPI([skuId])
      updateCart()
    } else {
      cartList.value = cartList.value.filter(item => item.skuId !== skuId)
    }
  }

  const changeCount = (skuId, count) => {
    const findResult = cartList.value.find(item => item.skuId === skuId)
    if (findResult) {
      findResult.count = count
    }
  }

  const changeSelected = (skuId, selected) => {
    const findResult = cartList.value.find(item => item.skuId === skuId)
    if (findResult) {
      findResult.selected = selected
    }
  }
  const changeAllSelected = (selected) => {
    cartList.value.forEach(item => {
      item.selected = selected
    })
  }

  const clearCart = async () => {
    // 清空购物车
    cartList.value = []
  }

  return {
    cartList,
    totalNumHeader,
    totalPriceHeader,
    totalNumSelected,
    totalPriceSelected,
    isAllSelected,
    updateCart,
    changeAllSelected,
    addCart,
    delCart,
    changeCount,
    changeSelected,
    clearCart
  }
}, {
  persist: true
})